Ext.onReady(function(){
    Ext.QuickTips.init();
    /**
     * ----------------------------------------------------
     *                 north
     *-----------------------------------------------------
     *   project     | setgrid| project      | schedule bar
     *               |        |              | ------------
     *               |        | setdetail    | breakgridpanel
     *  billingreport|       | breaklist    |
     *  ____________________________________________________
     *                    south
     * ------------------------------------------------------
     *
     *
     */
   
   var  projectpanel = new Ext.tree.TreePanel({
        id: 'project-panel',
        title: 'Projects',
        split: true,
        height: 300,
        minSize: 150,
        autoScroll: true,
		region: 'north',        
        // tree-specific configs:
        rootVisible: false,
        lines: false,
        singleExpand: true,
        useArrows: true,
        
        loader: new Ext.tree.TreeLoader({
            dataUrl: '/projects',
            baseParams: { //    action: 'projecttree'
}
        }),
        root: {
            nodeType: 'async',
            draggable: false,
            text: 'Projects',
            //this id is used to load the tree automatically
            id: 'root'
        }
    });
    
    /*
     * The data behind the project detail
     */
    var projectstore = new Ext.data.JsonStore({
    
        root: 'results',
        totalProperty: 'totalCount',
        idProperty: 'id',
        remoteSort: true,
        fields: ["cyl_hold_ct", "beam_hold_cost", "cube_ct", "cube_hold_ct", "cube_cost", "cube_price", "hold_price", "total", "no_days", "day_price", "cyl_cost", "beam_price", "cube_hold_cost", "client_name", "cyl_ct", "beam_hold_ct", "cyl_price", "project_name", "set_ct", "grand", "cyl_hold_cost", "days_cost", "set_price", "project_num", "beam_ct", "start_dt", "end_dt", "beam_cost"],
        
        proxy: new Ext.data.HttpProxy({
            //            url: '/project/getproject'
            url: '/project/projectcost'
        })
    });
    /*
     * new invoice window
     */
    var invoice_project_store = new Ext.data.JsonStore({
        proxy: new Ext.data.HttpProxy({
            url: '/invoices?node=list_project'
        })
    });
    var invoice_client_store = new Ext.data.JsonStore({
        proxy: new Ext.data.HttpProxy({
            url: '/invoices?node=list_client'
        })
    });
    
    var invoice_client_combo = new Ext.form.ComboBox({
        store: invoice_client_store,
        displayField: 'client_name',
        typeAhead: false,
        mode: 'remote',
        triggerAction: 'all',
        emptyText: 'Select a client...',
        selectOnFocus: true,
        fieldLabel: 'Client',
        name: 'client_name',
		allowBlank:false

    });
    
    invoice_client_combo.on('select', function(combo, record){
        var client_name = invoice_client_combo.getValue();
        invoice_project_store.setBaseParam('client_name', client_name);
    })
    
    var invoice_project_combo = new Ext.form.ComboBox({
        store: invoice_project_store,
        displayField: 'project_name',
        name: 'project_name',
        typeAhead: false,
        mode: 'remote',
        triggerAction: 'all',
        emptyText: 'Select a project...',
        selectOnFocus: true,
        fieldLabel: 'Project',
		allowBlank:false

    });
    invoice_project_combo.on('select', function(combo, record){
    
        invoice_job_number.setValue(record.get('project_number'))
    });
    
    var invoice_job_number = new Ext.form.TextField({
        fieldLabel: 'Job Number',
		name: 'project_number',
		allowBlank:false

    });
	
  
    
    var new_invoice_form = new Ext.FormPanel({
        labelWidth: 75,
        url: '/invoices?node=insert',
        frame: true,
        width: 350,
        defaults: {
            width: 230
        },
        defaultType: 'textfield',
        items: [new Ext.form.DateField({
            fieldLabel: 'Invoice Date',
            name: 'invoice_date',
            id: 'dt-invoice-date',
			allowBlank:false

        }), new Ext.form.DateField({
            fieldLabel: 'From',
            name: 'invoice_from',
			allowBlank:false

        }), new Ext.form.DateField({
            fieldLabel: 'To',
            name: 'invoice_to',
			allowBlank:false
        }), invoice_client_combo, invoice_project_combo, invoice_job_number, {
            xtype: 'radiogroup',
            columns: 2,
			allowBlank: false,
            fieldLabel: 'Testing Type',
            items: [{
            
                boxLabel: 'Compaction',
                name: 'testing_type',
                inputValue: 'compaction'
            }, {
                boxLabel: 'Asphalt',
                name: 'testing_type',
                inputValue: 'asphalt'
            }]
        }],
        buttons: [{
            text: 'Save',
            handler: function(){
                if (new_invoice_form.getForm().isValid()) {
                    new_invoice_form.getForm().submit({
                        url: '/invoices?node=insert',
                        waitMsg: 'Creating new invoice...',
                        success: function(fp, o){
                            Ext.MessageBox.alert('Status', 'New Invoice Created');
							new_invoice_form.getForm().reset();
							new_invoice_window.hide();
							invoice_panel.getLoader().load(invoice_panel.getRootNode())
                        }
                    });
                } else {
					Ext.MessageBox.alert('Validation Error', 'Fix the errors on the form');
				}
            }
        }, {
            text: 'Close',
            handler: function(){
				new_invoice_form.getForm().reset();
                new_invoice_window.hide()
            }
        }]
    
    });
    var new_invoice_window = new Ext.Window({
        modal: true,
        id: 'new-invoice-window',
        layout: 'fit',
        width: 500,
        height: 300,
        closeAction: 'hide',
        plain: true,
        title: 'New Invoice',
        items: [new_invoice_form]
    });
    
    /*
     * invoice store
     */
    var invoice_panel = new Ext.tree.TreePanel({
        id: 'invoice-panel',
        title: 'Invoices',
        height: 300,
        minSize: 150,
        autoScroll: true,
        region: 'north',
        tbar: new Ext.Toolbar({
            items: [ 
            {
                xtype: 'button',
                text: 'New Invoice',
				iconCls:'dlzbutton',
                id: 'button-new-invoice',
                handler: function(){
                    new_invoice_window.show()
                }
				
            }, {
					xtype: 'button',
					text: 'Delete Invoice',
					iconCls:'dlzbutton',
					handler: function(){
						var node = invoice_panel.getSelectionModel().getSelectedNode();
						if (node){
							Ext.Ajax.request({
								url: '/invoices',
								params:{rid: node.id, node: 'delete_invoice'},
								method: 'POST',
								success: function(r){
									invoice_panel.getLoader().load(invoice_panel.getRootNode());
									Ext.MessageBox.alert('Status', 'Invoice deleted');
									
									
								},
								failure: function(){
									Ext.MessageBox.alert('Status', 'Failed to delete invoice');
								}
							})
						
						} else {
							Ext.MessageBox.alert('Info', 'No Invoice is selected.')
						}
					}
				}]
        }),
        
        // tree-specific configs:
        rootVisible: false,
        lines: false,
        singleExpand: true,
        useArrows: true,
        
        loader: new Ext.tree.TreeLoader({
            dataUrl: '/projects',
            baseParams: { //    action: 'projecttree'
}
        }),
        root: {
            nodeType: 'async',
            draggable: false,
            text: 'Invoices',
            //this id is used to load the tree automatically
            id: 'root'
        }
    });
    

    
    /*
     * testgrid
     * This list all the tests for selected project or break
     */
    teststore = new Ext.data.JsonStore({
        proxy: new Ext.data.HttpProxy({
            url: '/testings'
        }),
		remoteSort: true
    });
	
	/*
     * continentGroupRow at this point is:
     * [
     *     {header: 'Asia', colspan: 4, align: 'center'},
     *     {header: 'Europe', colspan: 6, align: 'center'}
     * ]
     * 
     * cityGroupRow at this point is:
     * [
     *     {header: 'Beijing', colspan: 2, align: 'center'},
     *     {header: 'Tokyo', colspan: 2, align: 'center'},
     *     {header: 'Berlin', colspan: 2, align: 'center'},
     *     {header: 'London', colspan: 2, align: 'center'},
     *     {header: 'Paris', colspan: 2, align: 'center'}
     * ]
     */
	rows = [
	{header: 'No', colspan: 2, align: 'center'},
	{header: 'General', colspan: 4, align: 'center'},
	{header: 'Field Test Data', colspan: 3, align: 'center'},
	{header: 'Control Data', colspan: 3, align: 'center'},
	{header: 'Compaction', colspan: 2, align: 'center'},
	{header: 'Results', colspan: 1, align: 'center'}
	];
	
	
    var group = new Ext.ux.grid.ColumnHeaderGroup({
        rows: [rows]
    });
	
	var columns = [
		new Ext.grid.RowNumberer(),
		{
            id: 'id',
            header: "id",
            width: 60,
            sortable: true,
            dataIndex: 'id',
            hidden: true
        },{
            header: "Test No",
            width: 50,
            sortable: true,
            dataIndex: 'test_no',
            hidden: false
			
        }, {
            header: "Date",
            width: 50,
            sortable: true,
            dataIndex: 'date_',
            hidden: false
        },{
            header: "Location",
            width: 50,
            sortable: true,
            dataIndex: 'test_location',
			hidden: false
        },{
            header: "Interval",
            width: 50,
			sortable: true,
            dataIndex: 'test_interval',
            hidden: false
        }, {
            header: "Wet Unit Weight",
            width: 50,
            sortable: true,
            dataIndex: 'wet_unit_weight',
			hidden: false
        }, {
            header: "Moisture Content(%)",
            width: 50,
            sortable: true,
            dataIndex: 'moisture_contentfield',
			hidden: false
        },{
            header: "Dry Unit Weight(pcf)",
            width: 50,
            sortable: true,
            dataIndex: 'dry_unit_weight',
			hidden: false
        }, {
            header: "Curve No.",
            width: 50,
            sortable: true,
            dataIndex: 'curve_no',
			hidden: false
        }, 
		 {
            header: "Max dry unit weight",
            width: 50,
            sortable: true,
            dataIndex: 'max_dry_unit_weight',
            hidden: false
        },{
            header: "Optium Moisture Content(%)",
            width: 50,
            sortable: true,
            dataIndex: 'optimum_moisture_content',
            hidden: false
        }, {
            header: "Specified(%)",
            width: 50,
            sortable: true,
            dataIndex: 'specified',
            hidden: false
        },
		{
            header: "Obtained(%)",
            width: 50,
            sortable: true,
            dataIndex: 'obtained',
            hidden: false
        },
		
		{
            header: "Remarks",
            width: 50,
            sortable: true,
            dataIndex: 'remarks',
            hidden: false
        }
		];

    
    var LIMIT = 25;
    var testgridpanel = new Ext.grid.GridPanel({
        store: teststore,
        loadMask: true,
        id: 'testgrid-panel',
        tbar: new Ext.Toolbar({
            items: [ 
            {
                xtype: 'button',
				iconCls:'dlzbutton',
                text: 'Download Invoice',
                handler: function(){
					var node = invoice_panel.getSelectionModel().getSelectedNode();
					if (node){
						var url = '/projects?' +	Ext.urlEncode({
							project_number: node.attributes.project_number,
							invoice_from: node.attributes.invoice_from,
							invoice_to: node.attributes.invoice_to,
							node: 'download'
						})
						
						location.href = url
					
					}
                    
                }
				
            }, {
					xtype: 'button',
					text: 'Upload Invoice',
					iconCls:'dlzbutton',
					handler: function(){
						alert('not working yet')
					}
				}]
        }),
        columns: columns,
        listener: {
            viewready: function(g){
                g.getSelectionModel().selectFirstRow()
            }
        },
		

        viewConfig: {
            forceFit: true
        },
		plugins: group,

        // paging bar on the bottom
        bbar: new Ext.PagingToolbar({
            pageSize: LIMIT,
            store: teststore,
            displayInfo: true,
            displayMsg: 'Displaying topics {0} - {1} of {2}',
            emptyMsg: "No topics to display"
        }),
        frame: false,
        //        width: 600,
        height: 600,
        autoScroll: true,
        //        collapsible: true,
        
        animCollapse: false,
		region: 'center',
        
        title: 'Testing List'
    });
    
    
    
    

    

    
    /*
     * west panel
     */
    var westpanel = {
        layout: 'border',
        id: 'west-panel',
        title: 'DLZ FIELD TESTING DATABASE',
        region: 'west',
        border: true,
        collapsible: true,
        split: true,
        margins: '2 0 5 5',
        width: 275,
        minSize: 100,
        maxSize: 500,
        items: [invoice_panel, {
            region: 'center',
            id: 'testing-detail-panel',
            title: 'Testing Detail',
			autoScroll: true
        }]
    };
    
    /*
     * viewport
     */
    var viewport = new Ext.Viewport({
        layout: 'border',
        items: [new Ext.BoxComponent({ // raw element
            region: 'north',
            el: 'header',
            height: 25
            //			bodyStyle: 'padding:5px 5px 15px 5px'
        }), //west
 westpanel, //center
        {
        
            region: 'center', // this is what makes this panel into a region within the containing layout
            layout: 'border',
            margins: '2 2 2 0',
			split: true,
            border: false,
            items: [testgridpanel]
        }, new Ext.BoxComponent({ // raw element
            region: 'south',
            el: 'footer',
            height: 16
        })]
    });
    
    
    
    /*
     * UI logic
     */
    
    /*
     * when a set is selected in the setgrid panel
     */
    testgridpanel.getSelectionModel().on('rowselect', function(sm, rowIdx, r){
    
        //        setdetailstore.setBaseParam('project', r.data.project_num);
        //        setdetailstore.setBaseParam('set', r.data.set_num);
        //        setdetailstore.load();
        var html = '<table border="0.5" style="font-size: 10px">';
        for (var name in r.data) {
            html = html + '<tr><td>' + name + '</td><td>' + r.data[name] + '</td></tr>'
        };
        html = html + '</table>';
        Ext.getCmp('testing-detail-panel').body.update(html);
        
        
        
    });
	
	invoice_panel.getSelectionModel().on('selectionchange', function(sm, node){
		if (node.isLeaf()) {
			testgridpanel.setTitle(String.format('{0}({1}) Date: {2}',node.attributes.project_name,node.attributes.project_number,node.attributes.date))
			teststore.load({params: {tableid:node.id, start:0, limit: LIMIT}})	
		}
		x = node;
		
	})
    
    
    /*
     * Initialize UI
     */
	
	
    
    
});

